use strict;
use warnings;

package JasPerl::EL::Util;
use parent qw{ Exporter };

use JasPerl::Util::Boolean;
use JasPerl::Util::Number;
use Scalar::Util qw{ blessed looks_like_number };

our @EXPORT_OK = qw{ coerce_boolean coerce_number coerce_string compare };

sub coerce_boolean {
    # TODO: undef, refs
    my $value = shift;
    return JasPerl::Util::Boolean::FALSE unless defined $value;
    return $value if eval { $value->isa('JasPerl::Util::Boolean') };
    return JasPerl::Util::Boolean->from($value);
}

sub coerce_number {
    # TODO: undef, refs, Math::*.pm
    my $value = shift;
    return JasPerl::Util::Number::new(0) unless defined $value;
    return $value if eval { $value->isa('JasPerl::Util::Boolean') };
    return JasPerl::Util::Number->from($value);
}

sub coerce_string {
    my $value = shift;
    return '' unless defined $value;
    return $value;
}

sub compare {
    my ($lhs, $rhs) = @_;
    # TODO: check specs
    if (ref $lhs || ref $rhs) {
        print STDERR "Compare $lhs with $rhs\n";
        return $lhs <=> $rhs;
    }
    if (looks_like_number $lhs && looks_like_number $rhs) {
        return $lhs <=> $rhs;
    }
    return $lhs cmp $rhs;
}

1;
